package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 购物车
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired(required = false)
    private ShoppingCartService shoppingCartService;

    /**
     * 作用: 添加购物车
     * @param shoppingCart   当前提交的购物项的数据
     * @param session
     * @return
     */

    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart, HttpSession session) {
        //获取当前登录者
        Long userId = (Long) session.getAttribute("user");
        //补全信息
        shoppingCart.setUserId(userId);
        //添加成功,将当前的购物项返回
        shoppingCart = shoppingCartService.add(shoppingCart);
        return R.success(shoppingCart);
    }

    /**
     * 作用: 查看购物车
     * @param session
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(HttpSession session){
        //获取当前登录者
        final Long userId = (Long) session.getAttribute("user");
        //根据当前登录者查看购物车
        List<ShoppingCart> shoppingCartList=shoppingCartService.findShoppingCartByUserId(userId);
       return R.success(shoppingCartList);
    }
    /**
     * 作用: 删除购物车
     * @param session
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean(HttpSession session){
        //1. 获取当前用户
       Long userId=(Long)session.getAttribute("user");
       //2.清空购物车
        shoppingCartService.clean(userId);
        return R.success("成功清空购物车");
    }
    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        //获取当前登录者
        final Long userId =(Long)session.getAttribute("user");
        shoppingCart.setUserId(userId);
        shoppingCart = (ShoppingCart) shoppingCartService.sub(shoppingCart);
        return R.success(shoppingCart);

    }

}
